package com.ruoyi.web.controller.okr;

import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.framework.util.ShiroUtils;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.domain.resultMapper.OkrAlignResult;
import com.ruoyi.system.domain.resultMapper.SynergiesResult;
import com.ruoyi.system.domain.resultMapper.SynergyOkrInfo;
import com.ruoyi.system.domain.resultMapper.SynergyUserResult;
import com.ruoyi.system.service.*;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 协同关系Controller
 *
 * @author xiaoshuai2233@sina.com
 * @date 2020-05-07
 */
@Controller
@RequestMapping("/okr/synergy")
public class MyOkrSynergyController extends BaseController {
    private String prefix = "okr";

    @Autowired
    private IOkrInfoService okrInfoService;


    @Autowired
    private IOkrCycleService okrCycleService;


    @Autowired
    private IOkrSynergyService okrSynergyService;

    @Autowired
    private ISysDeptService deptService;

    @Autowired
    private IOkrInformService informService;


    @Autowired
    private IOkrAlignInfoService okrAlignInfoService;

    @Autowired
    private IOkrSeatsService okrSeatsService;

    private AlignBase alignBase = new AlignBase();

//    @RequiresPermissions("okr:synergy:view")
//    @GetMapping()
//    public String synergy(ModelMap mmap) {
//        List<OkrCycle> list = okrCycleService.selectOkrCycleList(new OkrCycle());
//        mmap.put("cycleList", list);
//        return prefix + "/synergyInfo";
//    }
    private Long cycleId;

    @PostMapping("/getCycleId")
    @ResponseBody
    public void getCycleId(Long cycleId){
        this.cycleId = cycleId;
    }

    @GetMapping("/querySynergies")
    public String querySynergies(){
        return prefix + "/synergies";
    }

    @PostMapping("/SynergiesList")
    @ResponseBody
    public TableDataInfo synergiesList(){
        SysUser user = ShiroUtils.getSysUser();
        List<SynergiesResult> synergiesResults = okrSynergyService.selectSynergies(user.getUserId(), cycleId);
        return getDataTable(synergiesResults);
    }

    @PostMapping("/cancelSynergy")
    @ResponseBody
    public AjaxResult cancelSynergy(Long userId, Long okrId){
        System.out.println(userId);
        System.out.println(okrId);
        //若员工有对齐的，也把对齐关系删掉
        okrSynergyService.deleteSynergyByLeader(userId, okrId);
        //删除协同
        okrSynergyService.deleteOkrSynergyByUserId(userId, okrId);
        return AjaxResult.success("删除协同成功");
    }

    /**
     * 查询OKR信息列表
     */
    @RequiresPermissions("okr:synergy:list")
    @PostMapping("/list")
    @ResponseBody
    public List<SynergyOkrInfo> list(OkrInfo okrInfo) {
        Long userId = ShiroUtils.getUserId();
        //设置默认周期
        if (okrInfo.getCycleId()==null) {
            okrInfo.setCycleId(getUseCycleId());
        }
        List<SynergyOkrInfo> list = okrInfoService.querySynergyOkrInfoListByUserId(okrInfo, userId);
        list = changeSynergyOkr(list);
        return list;
    }

    public Long getUseCycleId()
    {
        List<OkrCycle> okrCycles = okrCycleService.selectOkrUseCycleList();
        for(int i=0;i<okrCycles.size();i++)
        {
            OkrCycle cycle = okrCycles.get(i);
            if(cycle.getCycleType().equals(0L))
            {
                return cycle.getId();
            }
        }
        return null;
    }

    @GetMapping("/querySynergy/{id}")
    public String querySynergy(@PathVariable("id") Long id, Model model){
        SysUser user = ShiroUtils.getSysUser();
        alignBase.setUserId(user.getUserId());
        alignBase.setOkrId(id);
        alignBase.setDeptId(user.getDeptId());
        model.addAttribute("source", id);
        return prefix + "/synergyUserList";
    }

    @PostMapping("/userList")
    @ResponseBody
    public TableDataInfo showUserList(){
        List<SynergyUserResult> synergyUserResults = okrSynergyService.selectSynergyUserList(alignBase);
        return getDataTable(synergyUserResults);
    }

    @PostMapping("/addSynergy")
    @ResponseBody
    public AjaxResult addSynergy(OkrSynergy okrSynergy){
        SysUser user = ShiroUtils.getSysUser();
        List<Long> userIds = okrSeatsService.selectSeatUsersByUserId(user.getUserId(), okrSynergy.getOkrId());
        for (Long userId : userIds){
            if (okrSynergy.getUserId().equals(userId)){
                return AjaxResult.error("OKR已对该用户设置私密，无法协同");
            }
        }
        okrSynergyService.insertOkrSynergy(okrSynergy);
        OkrInfo okrInfo = okrInfoService.selectOkrInfoById(okrSynergy.getOkrId());
        OkrInform okrInform = new OkrInform();
        okrInform.setParentName(user.getUserName());
        okrInform.setContent("将[ " + okrInfo.getContent() + " ]协同给您对齐");
        okrInform.setParentId(user.getUserId());
        okrInform.setUserId(okrSynergy.getUserId());
        okrInform.setUrl("okr/info/view/" + okrSynergy.getOkrId());
        okrInform.setInformTime(DateUtils.getNowDate());
        informService.insertOkrInform(okrInform);

        //添加协同时通知协同的员工
        return AjaxResult.success("添加协同");
    }

    /**
     * 检测OKR是否被对齐，设置对齐状态
     *
     * @param list
     * @return
     */
    public List<SynergyOkrInfo> changeSynergyOkr(List<SynergyOkrInfo> list) {
        List<SynergyOkrInfo> resultList = new ArrayList<>();
        if (list != null && list.size() > 0) {
            Long userId = ShiroUtils.getUserId();
            OkrInfo okrInfo = new OkrInfo();
            okrInfo.setUserId(userId);
            List<OkrAlignResult> okrInfoList = okrInfoService.queryMyOkrAlignListByUserId(okrInfo);
            Map<String,String> map = okrInfoService.getMyOkrParentIds(okrInfoList);
            for (int i = 0; i < list.size(); i++) {
                SynergyOkrInfo synergyOkrInfo = list.get(i);
                if (map.containsKey(synergyOkrInfo.getId().toString())) {
                    synergyOkrInfo.setAlign(true);
                } else {
                    synergyOkrInfo.setAlign(false);
                }
                resultList.add(synergyOkrInfo);
            }
        }
        return resultList;
    }



}
